#!/usr/bin/env python
# -*- coding: utf-8 -*-
# @Time    : 2021/7/14
# @Author  : LiJun
# @Email   : lijun@tianyancha.com
# @Version : 1.0.0
import json

import mitmproxy.http

from mitmproxy import ctx


class Rewrite:

    def response(self, flow: mitmproxy.http.HTTPFlow):
        """
            The full HTTP response has been read.
        """
        if "https://stock.xueqiu.com/v5/stock/batch/quote.json?_t=" in flow.request.pretty_url and "x=" in flow.request.pretty_url:
            ctx.log.info(f"==========\n {flow.response.text}")
            response_data = json.loads(flow.response.text)
            response_data['data']['items'][0]['quote']['name'] = "奶粉钱_rewrite"
            response_data['data']['items'][0]['quote']['percent'] = 0.0
            response_data['data']['items'][1]['quote']['percent'] = +1.0
            response_data['data']['items'][2]['quote']['percent'] = -2.0
            new_data = self.multiple_float(response_data, 3)
            flow.response.text = json.dumps(new_data)

    def multiple_float(self, data, multiple=1):
        if isinstance(data, dict):
            for k, v in data.items():
                data[k] = self.multiple_float(v, multiple)
        elif isinstance(data, list):
            data = [self.multiple_float(i, multiple=multiple) for i in data]
        elif isinstance(data, float):
            data = data * multiple
        else:
            data = data
        return  data


addons = [
    Rewrite()
]


if __name__ == '__main__':
    from mitmproxy.tools.main import mitmdump

    mitmdump(['-p', '8080', '-s', __file__])
